import React, { useState } from 'react';
import {
  Row,
  Col,
  Form,
  Select,
  Input,
  Button,
  DatePicker,
  Table,
  Modal,
  message,
  Alert,
  Badge,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { history } from 'umi';
import request from '../../../http';
import { askForLeave } from '@/pages/login/service';
import TextArea from 'antd/lib/input/TextArea';
const { Option } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker;

export default function index() {
  const [formObject] = Form.useForm(); //获取数据
  const [form] = Form.useForm(); //获取数据
  const tableTitle: any[] = [
    //数据表头
    { title: '申请提交日期', dataIndex: 'submitTime' },
    { title: '院系', dataIndex: 'collegesName' },
    { title: '专业', dataIndex: 'majorName' },
    { title: '年级', dataIndex: 'gradeName' },
    { title: '班级', dataIndex: 'className' },
    { title: '学号', dataIndex: 'userNo' },
    {
      title: '姓名',
      dataIndex: 'stuName',
      render: (stuName: any) => {
        return <span style={{ color: '#EA0000' }}>{stuName}</span>;
      },
    },
    { title: '主题', dataIndex: 'theme' },
    { title: '请假原因', dataIndex: 'leaveType' },
    { title: '原因说明', dataIndex: 'reason' },
    { title: '请假开始时间', dataIndex: 'startLeaveTime' },
    { title: '请假结束时间', dataIndex: 'endLeaveTime' },
    {
      title: '审批状态',
      dataIndex: 'status',
      render: (status: any) => {
        return (
          <Badge
            color={
              status == '审批不通过'
                ? 'gold'
                : status == '审批通过'
                ? 'green'
                : 'blue'
            }
            text={status}
          />
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'tag',
      render: (text: any, record: any) => (
        <>
          {record.status == '待审批' ? (
            <Button
              type="link"
              onClick={() => {
                askForLeave.saveAskForLeaveId({
                  id: record.leaveId,
                  status:
                    record.status == '待审批'
                      ? 0
                      : record.status == '审批不通过'
                      ? 1
                      : 2,
                  role: 2,
                  info: record,
                  key: 0,
                });
                history.push('/global/askForLeave/particulars');
              }}
            >
              处理
            </Button>
          ) : (
            <Button
              type="link"
              onClick={() => {
                askForLeave.saveAskForLeaveId({
                  id: record.leaveId,
                  status:
                    record.status == '待审批'
                      ? 0
                      : record.status == '审批不通过'
                      ? 1
                      : 2,
                  role: 2,
                  info: record,
                  key: 1,
                });
                history.push('/global/askForLeave/particulars');
              }}
            >
              详情
            </Button>
          )}
        </>
      ),
    },
  ];

  const [pagination, setPagination] = React.useState({
    //分页器
    current: 1,
    total: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '50', '200', '500'],
    showQuickJumper: true,
    defaultPageSize: 5,
    // showTotal:(total:any, current:any) => `共 ${total} 条记录  第 ${current[0]}/${current[1]} 页`,
  });

  const [College, setCollege] = useState<
    { key: number; name: string; id: number }[]
  >([]);
  const [Major, setMajor] = React.useState<
    { key: number; name: string; id: number }[]
  >([]);
  const [Grade, setGrade] = React.useState<
    { key: number; name: string; id: number }[]
  >([]);
  const [ClassInfo, setClassInfo] = React.useState<
    { key: number; name: string; id: number }[]
  >([]);
  const loadDataSource = async () => {
    await request
      .post('/api/common_module/a_t_s/getCollege')
      .then((response: any) => {
        if (response.code == 200) {
          const data = response.data.map((item: any, index: number) => ({
            key: item.collegeId,
            id: item.collegeId,
            name: item.collegeName,
          }));
          setCollege(data);
        } else {
          message.error(response.message);
        }
      });
    await request
      .post('/api/common_module/a_t_s/getMajor')
      .then((response: any) => {
        if (response.code == 200) {
          const data = response.data.map((item: any, index: number) => ({
            key: item.majorId,
            id: item.majorId,
            name: item.majorName,
          }));
          setMajor(data);
        } else {
          message.error(response.message);
        }
      });
    await request
      .post('/api/common_module/a_t_s/getGrade')
      .then((response: any) => {
        if (response.code == 200) {
          const data = response.data.map((item: any, index: number) => ({
            key: item.gradeId,
            id: item.gradeId,
            name: item.gradeName,
          }));
          setGrade(data);
        } else {
          message.error(response.message);
        }
      });
    await request
      .post('/api/common_module/a_t_s/getClassInfo')
      .then((response: any) => {
        if (response.code == 200) {
          const data = response.data.map((item: any, index: number) => ({
            key: item.classId,
            id: item.classId,
            name: item.className,
          }));
          setClassInfo(data);
        } else {
          message.error(response.message);
        }
      });
  };

  const [dataSource, setDataSource] = React.useState<any[]>(); //数据集合
  const getData = async (pageValue: any, pageSizeValue: any, data: any) => {
    let datas =
      (data.subTime == undefined
        ? ''
        : 'startLeaveTime=' +
          moment(data.subTime[0]).format('YYYY-MM-DD HH:mm:ss')) +
      (data.subTime == undefined
        ? ''
        : '&endLeaveTime=' +
          moment(data.subTime[1]).format('YYYY-MM-DD HH:mm:ss')) +
      (data.classId == undefined ? '' : '&classId=' + data.classId) +
      (data.collegeId == undefined ? '' : '&collegeId=' + data.collegeId) +
      (data.gradeId == undefined ? '' : '&gradeId=' + data.gradeId) +
      (data.leaveType == undefined ? '' : '&leaveType=' + data.leaveType) +
      (data.majorId == undefined ? '' : '&majorId=' + data.majorId) +
      (data.status == undefined ? '' : '&status=' + data.status) +
      (data.stuName == undefined ? '' : '&stuName=' + data.stuName) +
      (data.theme == undefined ? '' : '&theme=' + data.theme) +
      (data.userNo == undefined ? '' : '&userNo=' + data.userNo);
    await request
      .get(
        '/api/teacher/queryStuLeaveForTea?' +
          datas +
          '&current=' +
          pageValue +
          '&size=' +
          pageSizeValue,
      )
      .then((response: any) => {
        if (response.code == 200) {
          const data = response.data.records.map(
            (item: any, index: number) => ({
              key: item.leaveId,
              leaveId: item.leaveId,
              submitTime: item.submitTime,
              collegesName: item.collegesName,
              majorName: item.majorName,
              gradeName: item.gradeName,
              className: item.className,
              userNo: item.userNo,
              stuName: item.stuName,
              theme: item.theme,
              leaveType:
                item.leaveType == 0
                  ? '病假'
                  : item.leaveType == 1
                  ? '事假'
                  : '其它',
              reason: item.reason,
              startLeaveTime: item.startLeaveTime,
              endLeaveTime: item.endLeaveTime,
              status:
                item.status == 0
                  ? '待审批'
                  : item.status == 1
                  ? '审批不通过'
                  : '审批通过',
              tag: item.tag,
            }),
          );
          const newPageObject = {
            ...pagination,
            current: pageValue,
            pageSize: pageSizeValue,
            total: response.data.total,
          };
          setPagination(newPageObject);
          setDataSource(data);
          setloading(false);
        } else {
          message.error(response.message);
        }
      });
  };
  React.useEffect(() => {
    getData(1, 5, formObject.getFieldsValue());
    loadDataSource();
  }, []);

  const [selectedRows, setselectedRows] = useState<any>([]); //
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([]); //
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: any[], selectedRows: any[]) => {
      setselectedRows(selectedRows);
      setselectedRowKeys(selectedRowKeys);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.status === '审批通过' || record.status === '审批不通过',
      status: record.status,
    }),
  };
  const clearAll = () => {
    setselectedRowKeys([]);
  };
  const selectmessage = () => {
    return (
      <h3>
        已选择<span style={{ color: 'blue' }}>{selectedRowKeys.length}</span>项{' '}
        <Button
          disabled={selectedRowKeys.length > 0 ? false : true}
          type={'link'}
          onClick={clearAll}
        >
          清空
        </Button>
      </h3>
    );
  };
  const Allstudent = () => {
    let names = '';
    selectedRows.map((item: any) => {
      names += item.stuName + '、';
    });
    return names;
  };

  const pageOnChange = async (page: any) => {
    await getData(page.current, page.pageSize, formObject.getFieldsValue());
  };

  const [isModalVisible, setIsModalVisible] = useState(false);

  const Aa = async () => {
    await request
      .get(
        '/api/teacher/batchPassOrEliminate?leaveIds=' +
          selectedRowKeys.toString() +
          '&reason=' +
          '&tag=1',
      )
      .then((response: any) => {
        if (response.code == '200') {
          clearAll();
          getData(1, 5, formObject.getFieldsValue());
          message.success('操作成功！');
        } else {
          message.error(response.message);
        }
      });
  };

  const formItemLayout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 24,
    },
  };

  const [loading, setloading] = useState(true);
  return (
    <>
      <Row justify="center">
        <Col span={22}>
          <Form
            className="ant-advanced-search-form"
            form={formObject}
            {...formItemLayout}
            onFinish={async (values: any) => {
              await getData(pagination.current, pagination.pageSize, values);
            }}
          >
            <Row gutter={24}>
              <Col span={6}>
                <Form.Item label="提交时间" name="subTime">
                  <RangePicker showTime />
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="院系" name="collegeId">
                  <Select placeholder="请选择">
                    {College.map((item) => (
                      <Option value={item.id} key={item.key}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="专业" name="majorId">
                  <Select placeholder="请选择">
                    {Major.map((item) => (
                      <Option value={item.id} key={item.key}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="年级" name="gradeId">
                  <Select placeholder="请选择">
                    {Grade.map((item) => (
                      <Option value={item.id} key={item.key}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="班级" name="classId">
                  <Select placeholder="请选择">
                    {ClassInfo.map((item) => (
                      <Option value={item.id} key={item.key}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="学号" name="userNo">
                  <Input placeholder="精确查询"></Input>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="学员姓名" name="stuName">
                  <Input placeholder="支持模糊查询"></Input>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="主题" name="theme">
                  <Input placeholder="请录入" />
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="请假原因" name="leaveType">
                  <Select placeholder="请选择">
                    <Option value={0} key="病假">
                      病假
                    </Option>
                    <Option value={1} key="事假">
                      事假
                    </Option>
                    <Option value={2} key="其它">
                      其它
                    </Option>
                  </Select>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item label="审批状态" name="status">
                  <Select placeholder="请选择">
                    <Option value={0} key="待审批">
                      待审批
                    </Option>
                    <Option value={2} key="审批通过">
                      审批通过
                    </Option>
                    <Option value={1} key="审批不通过">
                      审批不通过
                    </Option>
                  </Select>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{ margin: '0 8px' }}
                  onClick={() => {
                    formObject.resetFields();
                  }}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
        </Col>
        <Col span={22}>
          <Button
            type="primary"
            style={{ marginRight: 20 }}
            disabled={selectedRowKeys.length > 0 ? false : true}
            onClick={() => {
              confirm({
                title: '请确认是否审批通过以下学生请假申请？',
                icon: <ExclamationCircleOutlined />,
                content: Allstudent(),
                onOk() {
                  Aa();
                },
                onCancel() {
                  message.warning('已取消！！');
                },
              });
            }}
          >
            审批通过
          </Button>
          <Button
            type="primary"
            disabled={selectedRowKeys.length > 0 ? false : true}
            onClick={() => {
              setIsModalVisible(true);
            }}
          >
            审批不通过
          </Button>
          <Modal
            title="不通过原因"
            visible={isModalVisible}
            footer={false}
            onCancel={() => {
              setIsModalVisible(false);
            }}
          >
            <Form
              form={form}
              name="nest-messages"
              onFinish={async () => {
                await request
                  .get(
                    '/api/teacher/batchPassOrEliminate?leaveIds=' +
                      selectedRowKeys.toString() +
                      '&reason=' +
                      form.getFieldsValue().reason +
                      '&tag=0',
                  )
                  .then((response: any) => {
                    if (response.code == '200') {
                      getData(1, 5, formObject.getFieldsValue());
                      message.success('操作成功！');
                    } else {
                      message.error(response.message);
                    }
                  });
              }}
            >
              <p>是否不通过{Allstudent()}的请假申请？</p>
              <Form.Item
                name="reason"
                rules={[{ required: true, message: '请输入不通过原因' }]}
              >
                <TextArea
                  placeholder="请输入不通过原因"
                  autoSize={{ minRows: 3, maxRows: 5 }}
                />
              </Form.Item>
              <Form.Item>
                <Button style={{ marginRight: 10 }} htmlType="submit">
                  确认
                </Button>
                <Button
                  onClick={() => {
                    setIsModalVisible(false);
                  }}
                >
                  取消
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        </Col>
        <Col span={22} style={{ marginTop: 20 }}>
          <Alert message={selectmessage()} type="info" showIcon />
          <Table
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            scroll={{ x: 2000 }}
            style={{ marginTop: 30 }}
            columns={tableTitle}
            dataSource={dataSource}
            pagination={pagination}
            onChange={pageOnChange} //分页、排序、筛选变化时触发(用以重新获取数据)
            loading={loading}
          />
        </Col>
      </Row>
    </>
  );
}
